<template>
  <div class="flex space-x-5 h-full">
    <div class="bg-white rounded-content-wrap w-[286px] flex-shrink-0 p-5 text-main-title">
      <div class="font-semibold mb-5">用户角色</div>
      <div>
        <div
          v-for="role in roles"
          :key="role.id"
          class="
            rounded-content-wrap
            text-sm
            py-3
            px-2
            hover:bg-[#0062ff] hover:bg-opacity-5
            flex
            items-center
            justify-between
            cursor-pointer
          "
          :class="selectedRole === role.id ? `bg-[#0062ff] bg-opacity-5` : ''"
          @click="toggleUser(role)"
        >
          <div>{{ role.roleName }}</div>
          <div @click.stop>
            <el-dropdown>
              <i class="el-icon-more text-gray-600"></i>
              <el-dropdown-menu slot="dropdown" class="py-0">
                <a @click="editRole(role)">
                  <el-dropdown-item>编辑</el-dropdown-item>
                </a>
                <a @click="deleteRole(role)">
                  <el-dropdown-item>删除</el-dropdown-item>
                </a>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div class="text-primary cursor-pointer py-3 px-2" @click.stop="addRole">+新建角色</div>
      </div>
    </div>
    <div v-loading="getDetailLoading" class="space-y-5 flex-1">
      <div class="bg-white rounded-content-wrap p-5 text-sm space-y-2">
        <div class="text-main-title">{{ currentRole.roleName }}</div>
        <div class="text-main-tips">功能权限说明：{{ currentRole.roleDesc }}</div>
      </div>
      <div class="bg-white rounded-content-wrap p-5">
        <el-tabs v-model="activeName">
          <el-tab-pane label="功能权限" name="function">
            <el-tree
              ref="tree"
              class="custom-expand-tree"
              default-expand-all
              :data="treeData"
              :props="props"
              node-key="keyId"
              :default-checked-keys="defaultCheckedKeys"
              show-checkbox
            >
              <template #default="{ node, data }">
                <template v-if="node.level === 3">
                  <span>{{ data.name }}</span>
                </template>
                <div v-else>{{ data.name }}</div>
              </template>
            </el-tree>
            <div
              class="border-t border-gray-200 border-solid flex justify-center py-5 space-x-3 mt-5"
            >
              <!-- <el-button class="w-[120px]">取&nbsp;&nbsp;消</el-button> -->
              <el-button class="w-[120px]" type="primary" @click="upsertMenuList"
                >保&nbsp;&nbsp;存</el-button
              >
            </div>
          </el-tab-pane>
          <el-tab-pane label="数据权限" name="data">
            <div class="text-main-content text-sm mb-5">
              默认全部数据权限（包括：查询、编辑、批量导出、批量导入、删除)
            </div>
            <div>
              <el-radio-group v-model="radio" class="flex flex-col space-y-5">
                <el-radio v-for="right in dataRights" :key="right.value" :label="right.value">{{
                  right.name
                }}</el-radio>
              </el-radio-group>
            </div>
            <div
              class="border-t border-gray-200 border-solid flex justify-center py-5 space-x-3 mt-5"
            >
              <!-- <el-button class="w-[120px]">取&nbsp;&nbsp;消</el-button> -->
              <el-button class="w-[120px]" type="primary" @click="upsertDataPermission"
                >保&nbsp;&nbsp;存</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <UpsertRoleDialog ref="upsertRoleDialog"></UpsertRoleDialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapGetters } from 'vuex'
import { ActionsType } from '@/actions/system'
import UpsertRoleDialog from '@/components/admin/system/role/UpsertRoleDialog.vue'
import type { IMenu } from '@/api/role'
import { getRoleDetail } from '@/api/role'
import { ActionsType as UserActionsType } from '@/actions/user'
// import { deleteRoleById } from '@/api/role'
interface IRole {
  id: number
  name: string
  desc: string
}
function treeForEach(trees: IMenu[], fn) {
  for (let i = 0; i < trees.length; i++) {
    const node = trees[i]
    fn(node)
    if (node.children && Array.isArray(node.children)) {
      treeForEach(node.children, fn)
    }
  }
  return trees
}

export default Vue.extend({
  components: { UpsertRoleDialog },
  data() {
    return {
      selectedRole: 1,
      activeName: 'function',
      props: {
        label: 'name',
      },
      defaultCheckedKeys: [],
      //

      radio: 'Owner',
      getDetailLoading: false,
      treeData: [],
      treeVisible: false,
    }
  },
  head: {
    title: '权限管理',
  },
  computed: {
    ...mapGetters('system', {
      // treeData: 'rights',
      roles: 'roles',
      dataRights: 'dataRights',
    }),
    currentRole() {
      // @ts-ignore
      return this.roles.find((x: IRole) => x.id === this.selectedRole) || {}
    },
  },
  async mounted() {
    const res = await this.$store.dispatch(ActionsType.getRoles)
    if (res[0]) {
      this.toggleUser(res[0])
    }
  },
  methods: {
    addRole() {
      this.$refs.upsertRoleDialog.show()
    },
    editRole(role: IRole) {
      this.$refs.upsertRoleDialog.show(role)
    },
    async upsertMenuList() {
      const checkedNodes = this.$refs.tree?.getCheckedNodes()
      // console.log(checkedNodes, this.treeData)
      const checkedIds = checkedNodes.map((x) => x.keyId)

      treeForEach(this.treeData, (n) => {
        n.status = checkedIds.includes(n.keyId) ? 1 : 0
      })
      await this.$store.dispatch(ActionsType.upsertRole, {
        id: this.selectedRole,
        menuList: this.treeData,
      })
      this.$message.success('修改权限成功!')
      this.$store.dispatch(UserActionsType.setBaseInfo)
    },
    async upsertDataPermission() {
      const { id } = this.currentRole
      await this.$store.dispatch(ActionsType.upsertRole, {
        id,
        dataPermission: this.radio,
      })
      this.$message.success('修改数据权限成功!')
    },
    async deleteRole(role: IRole) {
      try {
        // console.log(role)
        await this.$confirm('您确定要删除该角色么？', '提示操作')
        await this.$store.dispatch(ActionsType.deleteRole, role.id)
        // await deleteRoleById(role.id)
        this.$message.success('删除成功!')
      } catch (error) {
        console.debug(error)
      }
    },

    async toggleUser(role: Record<string, any>) {
      // if (this.selectedRole === role.id) {
      //   this.selectedRole = -1
      // } else {
      this.treeVisible = false
      this.selectedRole = role.id

      try {
        this.getDetailLoading = true
        const res = await getRoleDetail(role.id)
        // console.log(res)
        this.radio = res.dataPermission
        this.treeData = res.menuList
        const defaultCheckedKeys = []
        treeForEach(this.treeData, (n) => {
          if (n.status === 1) {
            defaultCheckedKeys.push(n.keyId)
          }
        })
        this.defaultCheckedKeys = defaultCheckedKeys
        this.treeVisible = true
      } catch (err) {
        console.error(err)
      } finally {
        this.getDetailLoading = false
      }

      // }
    },
  },
})
</script>

<style lang="scss">
.custom-expand-tree {
  > .el-tree-node {
    //第一级
    > .el-tree-node__content {
      @apply mb-3;
    }
    > .el-tree-node__children {
      > .el-tree-node {
        // 第二级
        > .el-tree-node__content {
          @apply mb-3;
        }
        &.is-Checked {
          .el-tree-node__children {
            display: flex !important;
          }
        }
        .el-tree-node__children {
          display: flex !important;
          .el-tree-node__content {
            @apply mb-3 hover:bg-white;
          }
        }
      }
    }
  }
}
</style>
